<?php

class LikeController extends Controller
{
	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
	public function viewLike($id,$type)
	{
		switch ($type)
		{
			case 'list':
				$data = Listmusic::model()->view($id);
				break;
			case 'music':
				$data = Music::model()->view($id);
				break;
			case 'comment':
				$data = Comment::model()->view($id);
				break;
		}
		$other = json_decode($data['other']);
		$like = array();

		if(isset($other->like))
		{
			foreach ($other->like as $key => $value){
				$like[$key] = User::model()->viewIdNameAvatar($key);

				$user_id = Yii::app()->user->getId();
				$friend_id = $like[$key]['id'];

				$like[$key]['relation'] = FriendshipController::getRelation($user_id,$friend_id);
				$quantitySameFriend = FriendshipController::getQuantitySameFriend($user_id,$friend_id);
				$like[$key]['quantitySameFriend'] =  $quantitySameFriend['friends'];
			}
		}

		//$friend_id = $data['user']['id'];

		//$relation = FriendshipController::getRelation($user_id,$friend_id);

		return $like;
	}

	public function updateLike($user_id,$id,$type)
	{
		switch ($type)
		{
			case 'list':
				$ob = Listmusic::model()->findByPk($id);
				break;
			case 'music':
				$ob = Music::model()->findByPk($id);
				break;
			case 'comment':
				$ob = Comment::model()->findByPk($id);
				break;
		}
		$data = $ob->attributes;
		$other = json_decode($data['other']);
		if(!isset($other->like->$user_id))
		{
			$other->like->$user_id = 1;
			$data['other'] = json_encode($other);
			$data['like']++;
			$ob->attributes= $data;

			NotificationController::addNotification_Like($user_id,$id,$type);
			return $ob->save();
		}
		else
			return false;
	}

	public function unLike($user_id,$id,$type)
	{
		switch ($type)
		{
			case 'list':
				$ob = Listmusic::model()->findByPk($id);
				break;
			case 'music':
				$ob = Music::model()->findByPk($id);
				break;
			case 'comment':
				$ob = Comment::model()->findByPk($id);
				break;
		}
		$data = $ob->attributes;
		$other = json_decode($data['other']);

		if(isset($other->like->$user_id))
		{
			unset($other->like->$user_id);
			$data['other'] = json_encode($other);
			$data['like']--;
			$ob->attributes= $data;
			return $ob->save();
		}
		else
			return false;
	}
}
